package com.difsonapps.android.marker;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;    

import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.json.JSONException;
import org.json.JSONObject;    

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.difsonapps.android.marker.app.AppController;

public class UploadRequest extends Request<JSONObject> {
	private static final String FILE_PART_NAME = "file";
	private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
    private final File mImageFile;
	

private Listener<JSONObject> listener;
private Map<String, String> params;

public UploadRequest(String url, Map<String, String> params, Listener<JSONObject> reponseListener, ErrorListener errorListener, File imageFile) {
    super(Method.POST, url, errorListener);
    this.listener = reponseListener;
    this.params = params;
    mImageFile = imageFile;
    buildMultipartEntity();
}

public UploadRequest(int method, String url, Map<String, String> params, Listener<JSONObject> reponseListener, ErrorListener errorListener, File imageFile) {
    super(method, url, errorListener);
    this.listener = reponseListener;
    this.params = params;
    mImageFile = imageFile;
}

@Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
    return params;
};

@Override
public Map<String, String> getHeaders() throws com.android.volley.AuthFailureError {
    Map<String, String> headers = super.getHeaders();

    if (headers == null
            || headers.equals(Collections.emptyMap())) {
        headers = new HashMap<String, String>();
    }
    //headers.put("Accept", "application/json");

    AppController.getInstance().addSessionCookie(headers);
    Log.w("Header to send ", "Content of header : "+headers);
    return headers;
}



private void buildMultipartEntity()
{
   	mBuilder.addBinaryBody(FILE_PART_NAME, mImageFile, ContentType.create("image/jpeg"), mImageFile.getName());
   	mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
   	mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}

@Override
public String getBodyContentType()
{
    String contentTypeHeader = mBuilder.build().getContentType().getValue();
    return contentTypeHeader;
}

@Override
public byte[] getBody() throws com.android.volley.AuthFailureError
{
	/*Bitmap bmp = BitmapFactory.decodeFile(mImageFile.getAbsolutePath());
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	bmp.compress(CompressFormat.JPEG, 70, bos);*/
	
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try
    {
    	mBuilder.build().writeTo(bos);
    }
    catch (IOException e)
    {
        VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
    }
    
    return bos.toByteArray();
}

@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers));
        
        AppController.getInstance().checkSessionCookie(response.headers);
        System.out.println("Header : "+response.headers);
        Log.w("Header received", "Content of header : "+response.headers);
        
        
        return Response.success(new JSONObject(jsonString),
                HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
}

@Override
protected void deliverResponse(JSONObject response) {
    listener.onResponse(response);
}
}